const HisToday = require('./ORM');
const crawlerRequest = require('@/utils/crawlerRequest');

// 爬取数据
function spiderData(req, res) {
  let { date, content_id } = req.query;
  let url = `https://www.chazidian.com/d/${date}/${content_id}/`;
  crawlerRequest({ url })
    .then($ => {
      const title = $('.hist_actcont h1').text(); // 标题
      const rich_text = $('.hist_actcont')
        .prop('outerHTML')
        .replace(/<img.*?>/gi, ''); // 内容
      if (rich_text) {
        // 更新数据库
        updateDB(rich_text, content_id)
          .then(r => {
            console.log('数据库更新成功', r);
          })
          .catch(e => {
            console.log('数据库更新失败', e);
          });
      }
      res.api_success({
        title,
        rich_text
      });
    })
    .catch(() => {
      res.api_error('请求异常', 500);
    });
}

// 更新数据库
async function updateDB(val, content_id) {
  return await HisToday.update(
    {
      rich_text: val
    },
    {
      where: {
        content_id: content_id
      }
    }
  );
}

module.exports = async (req, res) => {
  const { content_id } = req.query;
  // 如果表不存在,则创建该表(如果已经存在,则不执行任何操作)
  await HisToday.sync();
  const project = await HisToday.findOne({
    where: { content_id },
    attributes: ['title', 'content_id', 'rich_text'] //返回特定字段
  });
  if (!project) {
    return res.api_error('数据库未找到该条数据', 1001);
  }
  if (project && project.rich_text) {
    return res.api_success(project);
  } else {
    spiderData(req, res);
  }
};
